﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Assignment_3.Classes;

namespace Assignment_3.Feature___Users
{
    public partial class AddUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["username"] == null || Session["usertype"] == null)
            {
                Response.Redirect("~/Feature - Users/Login.aspx");
            }

            if (((string)Session["usertype"]) != "Administrator")
            {
                Response.Redirect("~/Other - Error Pages/NoPermission.aspx");
            }
        }

        protected void createBtn_Click(object sender, EventArgs e)
        {
            Page.Validate();
            if (Page.IsValid)
            {
                UserAccount user = new UserAccount();
                Staff s = new Staff();
                int rowsInserted = 0;

                user.Username = tbxUsername.Text;
                user.UserType = ddlUserType.SelectedItem.Text;
                user.Password = tbxConfirmPassword.Text;

                s.Name = tbxName.Text;
                s.DOB = Convert.ToDateTime(tbxDOB.Text);
                s.BankNo = Convert.ToInt32(tbxBankNo.Text);
                s.Address = tbxAddress.Text;
                s.TelNo = Convert.ToInt32(tbxTelNo.Text);
                s.DutyType = ddlDutyType.SelectedItem.Text;
                s.Username = tbxUsername.Text;

                rowsInserted = DatabaseManager.CreateUserAccount(user);

                if (rowsInserted != 0)
                {
                    rowsInserted = 0;
                    rowsInserted = DatabaseManager.CreateStaff(s);

                    if (rowsInserted != 0)
                    {
                        string username = tbxUsername.Text.ToString();
                        string query = "ID=" + username;

                        Response.Redirect("~/Feature - Users/RetrieveUser.aspx?" + query);
                    }
                }
            }
        }

        protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
        {
            Staff s = DatabaseManager.GetStaffByUsername(tbxUsername.Text);
            args.IsValid = (s == null);
        }

        protected void tbxUsername_TextChanged(object sender, EventArgs e)
        {
            CustomValidator1.Validate();
        }
    }
}